﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace cs2335lab5
{
    namespace Server
    {
        /// <summary>
        /// Interaction logic for LoginForm.xaml
        /// </summary>
        public partial class ServerForm : Window
        {
            /// <summary>
            /// Public constructor; initializes GUI
            /// </summary>
            public ServerForm()
            {
                InitializeComponent();
            }

            /// <summary>
            /// Delegate to call WriteLine() from another thread
            /// </summary>
            /// <param name="text">text to write</param>
            delegate void writeLineDelegate(string text);

            /// <summary>
            /// WriteLine function that acts in a similar manner to Console.WriteLine
            /// </summary>
            /// <param name="text"></param>
            public void WriteLine(string text)
            {
                if (textBox.Dispatcher.CheckAccess())
                {
                    // the calling thread owns the dispatcher, and hence the UI element
                    textBox.Text += text;
                    textBox.Text += "\r\n";
                    textBox.ScrollToEnd();
                }
                else
                {
                    // invokation required
                    textBox.Dispatcher.Invoke(DispatcherPriority.Normal, new writeLineDelegate(WriteLine), text);
                }
            }

            private void Connect_Click(object sender, RoutedEventArgs e)
            {
                // check if we're connected
                if (App.Instance().Host == null)
                {
                    // if we're not, this is a connect call
                    App.Instance().Connect(serverTextBox.Text, portTextBox.Text);
                    Connect.Content = "Disconnect";
                    serverTextBox.IsEnabled = false;
                    portTextBox.IsEnabled = false;
                }
                else
                {
                    // if we are, this is a disconnect call
                    App.Instance().Disconnect();
                    Connect.Content = "Connect";
                    serverTextBox.IsEnabled = true;
                    portTextBox.IsEnabled = true;
                }
            }
        }
    }
}
